<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" show-summary class="-mt-10px">
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="产品名称" min-width="60">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.productId`" :rules="formRules.productId" class="mb-0px!">
            <el-select
              v-model="row.productId"
              clearable
              filterable
              @change="onChangeProduct($event, row)"
              placeholder="请选择产品"
              :filter-method="handleFilterMethod"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="产品价格" width="80">
        <template #default="{ row }">
          <el-form-item class="mb-0px!">
            {{ productUnitNameFun(row.productId) }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="终止日期" min-width="80">
        <template #default="{ row }">
          <el-date-picker
            v-model="row.productExpirationDate"
            type="date"
            value-format="x"
            placeholder="选择终止日期"
            class="!w-160px"
          />
        </template>
      </el-table-column>
      <el-table-column label="生效日期" min-width="80">
        <template #default="{ row }">
          <el-date-picker
            v-model="row.productEffectiveDate"
            type="date"
            value-format="x"
            placeholder="选择生效日期"
            class="!w-160px"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="60" fixed="right">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link type="primary">删除此条</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加物料价格关联</el-button>
  </el-row>
</template>
<script setup lang="ts">
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { StockApi } from '@/api/erp/stock/stock'
import { erpCountFormatter, erpPriceInputFormatter, erpPriceMultiply, getSumValue } from '@/utils'
import { ref, reactive, watch, onMounted } from 'vue'

const props = defineProps<{
  items?: any[]
  disabled?: boolean
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref<any[]>([])
const formRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '产品单价不能为空', trigger: 'blur' }],
  productExpirationDate: [{ required: true, message: '终止日期不能为空', trigger: 'blur' }],
  productEffectiveDate: [{ required: true, message: '生效日期不能为空', trigger: 'blur' }]
})
const formRef = ref<any>(null) // 表单 Ref
const productList = ref<ProductVO[]>([]) // 显示在下拉框中的产品列表
const productAllList = ref<ProductVO[]>([]) // 完整的产品列表

/** 初始化设置入库项 */
watch(
  () => props.items,
  async (val) => {
    if (val && val.length) {
      formData.value = val
      // 确保已选择的产品都在产品列表中
      await ensureSelectedProductsInList()
    }
  },
  { immediate: true }
)

/** 确保已选择的产品都在下拉列表中 */
const ensureSelectedProductsInList = async () => {
  if (productAllList.value.length === 0) {
    // 如果还没有加载完整列表，先加载
    await loadAllProducts()
  }

  // 获取所有已选择的产品ID
  const selectedProductIds = formData.value.map((item) => item.productId).filter(Boolean)

  // 检查这些产品是否都在当前显示的列表中
  selectedProductIds.forEach((productId) => {
    const existsInList = productList.value.some((item) => item.id === productId)
    if (!existsInList) {
      // 如果不在，从完整列表中找到并添加
      const product = productAllList.value.find((item) => item.id === productId)
      if (product) {
        productList.value.push(product)
      }
    }
  })
}

/** 加载所有产品 */
const loadAllProducts = async () => {
  const res = await ProductApi.getProductSimpleList()
  productAllList.value = res
  return res
}

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    productId: undefined,
    price: undefined,
    productExpirationDate: undefined,
    productEffectiveDate: undefined
  }
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index: number) => {
  formData.value.splice(index, 1)
}

/** 处理产品变更 */
const onChangeProduct = (productId, row) => {
  const product = productAllList.value.find((item) => item.id === productId)
  if (product) {
    row.price = product.purchasePrice
  }
}

// 处理单位回显
const productUnitNameFun = (productId: any) => {
  const product = productAllList.value.find((item) => item.id === productId)
  return product ? product.purchasePrice : ''
}

/** 表单校验 */
const validate = () => {
  return formRef.value?.validate()
}
defineExpose({ validate })

/** 处理过滤方法 */
const handleFilterMethod = async (query?: string) => {
  // 确保已加载所有产品
  if (productAllList.value.length === 0) {
    await loadAllProducts()
  }

  // 先获取所有已选择的产品，确保它们会被包含在结果中
  const selectedProducts = formData.value
    .map((item) => productAllList.value.find((p) => p.id === item.productId))
    .filter(Boolean)

  if (!query) {
    // 如果没有查询条件，显示前200条加上已选择的产品
    const topProducts = [...productAllList.value].slice(0, 200)
    // 合并并去重
    productList.value = Array.from(
      new Map([...topProducts, ...selectedProducts].map((item) => [item.id, item])).values()
    )
  } else {
    // 有查询条件时，显示匹配的产品加上已选择的产品
    const filteredProducts = productAllList.value.filter((d) =>
      d.name.toLowerCase().includes(query.toLowerCase())
    )
    // 合并并去重
    productList.value = Array.from(
      new Map([...filteredProducts, ...selectedProducts].map((item) => [item.id, item])).values()
    )
  }

  return productList.value
}

/** 初始化 */
onMounted(async () => {
  await loadAllProducts() // 加载所有产品
  await handleFilterMethod() // 初始化显示列表

  // 默认添加一个
  if (formData.value.length === 0) {
    handleAdd()
  } else {
    // 确保已有数据中的产品都在列表中
    await ensureSelectedProductsInList()
  }
})
</script>